package com.sto.stoapp.db.manager;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.sto.stoapp.db.StoDataBase;
import com.sto.stoapp.db.constant.RegionInfoConstant;
import com.sto.stoapp.db.constant.StoBaseConstant;
import com.sto.stoapp.db.constant.StoRouteConstant;
import com.sto.stoapp.entity.RouteEntity;
import com.sto.stoapp.http.response.download.info.RouteInfo;
import com.sto.stoapp.log.ExceptionLog;
import com.sto.stoapp.util.UnifiedStaticType;

import java.util.ArrayList;
import java.util.List;

/**
 * 路由表管理类
 * 
 * @author mgf
 * 
 */
public class RouteManager extends StoDataBase implements DownLoadDao<RouteInfo> {

	private static RouteManager manager;

	private static final String SQL_QUERY_ALL = "select * from " + TAB_ROUTE
			+ " where 1=1";

	private static final String SQL_QUERY_COUNT = "select count(*) from "
			+ TAB_ROUTE + " where 1=1";

	/** 按照路由号查找记录 */
	private static final String SQL_QUERY_BY_ROUTE = "select * from "
			+ TAB_ROUTE + " where " + ROUTE_CODE + " = ? ";

	private static final String SQL_FUZZY_QUERY_B_ROUTE = "select * from " +
			TAB_ROUTE+" where " +ROUTE_CODE+" like ?";

	private RouteManager(Context context) {
		super(context);
	}

	/**
	 * 单例化对象
	 * 
	 * @param context
	 * @return
	 */
	public static RouteManager getInstance(Context context) {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			if (manager == null) {
				manager = new RouteManager(context);
			}
			return manager;
		}
	}

	/**
	 * 插入单条数据
	 * 
	 * @param
	 * @return
	 */
	public boolean insert(RouteInfo info) {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			long res = -1;

			try {
				ContentValues values = buildContentValues(info);
				res = getSqliteDatabase(UnifiedStaticType.WRITE_DATABASE)
						.insert(TAB_ROUTE, null, values);
				if (res > 0) {
					Log.d("插入一条路由表记录", "成功");
				} else {
					Log.d("插入一条路由表记录", "失败");
				}
			} catch (Exception e) {
				e.printStackTrace();
				ExceptionLog.writeLog("insert", e.getMessage());
			} finally {
				closeDb(UnifiedStaticType.WRITE_DATABASE);
			}
			return res > 0 ? true : false;
		}
	}



	/**
	 * 查询路由表记录条数
	 * 
	 * @return
	 */
	public int queryAllCount() {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			int count = 0;
			Cursor cursor = getSqliteDatabase(UnifiedStaticType.READ_DATABASE)
					.rawQuery(SQL_QUERY_COUNT, null);
			if (cursor != null && cursor.moveToFirst()) {
				count = cursor.getInt(0);
			}
			closeCursor(cursor);
			closeDb(UnifiedStaticType.READ_DATABASE);
			return count;
		}
	}

	/**
	 * 查询所有数据
	 * 
	 * @return
	 */
	public List<RouteEntity> queryAll() {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			List<RouteEntity> data = getDataFromCursor(getSqliteDatabase(
					UnifiedStaticType.READ_DATABASE).rawQuery(SQL_QUERY_ALL,
					null));
			return data;
		}
	}

	public List<RouteEntity> queryFuzzyAll(String routeCode){
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED){
			List<RouteEntity> data = getDataFromCursor(getSqliteDatabase(
					UnifiedStaticType.READ_DATABASE)
					.rawQuery(SQL_FUZZY_QUERY_B_ROUTE,new String[]{"%" + routeCode + "%"}));
			return data;
		}
	}
	/**
	 * 根据路由号查找记录
	 * 
	 * @return
	 */
	public RouteEntity queryByRouteCode(String routeCode) {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			RouteEntity entity = null;
			Cursor c = getCursor(UnifiedStaticType.READ_DATABASE,
					SQL_QUERY_BY_ROUTE, new String[] { routeCode });
			if (c != null && c.moveToFirst()) {
				entity = getSingleData(c);
			}
			closeCursor(c);
			closeDb(UnifiedStaticType.READ_DATABASE);
			return entity;
		}
	}

	private List<RouteEntity> getDataFromCursor(final Cursor c) {
		List<RouteEntity> lstData = new ArrayList<RouteEntity>();
		if (c != null) {
			if (c.moveToFirst()) {
				do {
					lstData.add(getSingleData(c));
				} while (c.moveToNext());
			}
			closeCursor(c);
		}
		closeDb(UnifiedStaticType.READ_DATABASE);
		return lstData;
	}

	private RouteEntity getSingleData(Cursor c) {
		RouteEntity data = new RouteEntity();
		data.setRouteCode(c.getString(c.getColumnIndex(ROUTE_CODE)));
		data.setNextStation(c.getString(c.getColumnIndex(NEXT_STATION)));
		data.setCenterDes(c.getString(c.getColumnIndex(CENTER_DES)));
		data.setShift(c.getString(c.getColumnIndex(SHIFT)));
		data.setTranType(c.getString(c.getColumnIndex(TRAN_TYPE)));
		return data;
	}

	@Override
	public String getMaxVersion() {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			String version = "0";
			Cursor c = null;
			try {
				SQLiteDatabase db = getSqliteDatabase(UnifiedStaticType.READ_DATABASE);
				c = db.rawQuery(getMaxVersionSql(TAB_ROUTE), null);
				if (c != null && c.moveToNext()) {
					version = c.getString(c
							.getColumnIndex(StoBaseConstant.VERSION));
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				closeCursor(c);
				closeDb(UnifiedStaticType.READ_DATABASE);
			}
			return version;
		}
	}

	@Override
	public boolean replace(ContentValues values) {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			long result = 0;
			try {
				SQLiteDatabase db = getSqliteDatabase(UnifiedStaticType.WRITE_DATABASE);
				result = db.replace(TAB_ROUTE, null, values);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return result > 0;
		}
	}

	@Override
	public void deleteDataByStatus(String status) {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {

			try {
				SQLiteDatabase db = getSqliteDatabase(UnifiedStaticType.WRITE_DATABASE);
				db.delete(TAB_ROUTE, STATUS + "=?", new String[] { status });
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				closeDb(UnifiedStaticType.WRITE_DATABASE);
			}

		}
	}

	@Override
	public ContentValues buildContentValues(RouteInfo entity) {
		ContentValues values = new ContentValues();
		values.put(ROUTE_CODE, entity.routeCode);
		values.put(NEXT_STATION, entity.nextOrgCode);
		values.put(StoRouteConstant.VERSION, entity.version);
		values.put(CENTER_DES, entity.desOrgCode);
		values.put(StoRouteConstant.NEXT_ORG_NAME, entity.nextOrgName);
		values.put(StoRouteConstant.DES_ORG_NAME, entity.desOrgName);
		values.put(RegionInfoConstant.ID, entity.id);
		values.put(STATUS, entity.status);
		return values;
	}

	/**
	 * 插入多数据
	 * 
	 * @param
	 * @return
	 */
	@Override
	public void insertOrReplace(List<RouteInfo> datas) {

		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			SQLiteDatabase db = getSqliteDatabase(UnifiedStaticType.WRITE_DATABASE);
			try {
				db.beginTransaction();
				for (RouteInfo info : datas) {
					long res = -1;
					ContentValues values = buildContentValues(info);
					// res = db.insert(TAB_ROUTE, null, values);
					// if (res > 0) {
					// Log.d("插入一条路由表记录", "成功");
					// } else {
					if (replace(values)) {
						Log.d("插入一条路由表记录", "成功");
					} else {
						Log.d("插入一条路由表记录", "失败");
						// }
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
				ExceptionLog.writeLog("insertList", e.getMessage());
			} finally {
				datas.clear();
				db.setTransactionSuccessful();
				db.endTransaction();
				closeDb(UnifiedStaticType.WRITE_DATABASE);
			}
		}
	}
	@Override
	public void deleteAll() {

		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			long res = -1;
			try {
				res = getSqliteDatabase(UnifiedStaticType.WRITE_DATABASE)
						.delete(TAB_ROUTE, null, null);
			} catch (Exception e) {
				e.printStackTrace();
				ExceptionLog.writeLog("deleteAll", e.getMessage());
			} finally {
				closeDb(UnifiedStaticType.WRITE_DATABASE);
			}

		}

	}
}
